import React, {useEffect, useState, useRef} from 'react'

import {Button, Space, message, Popconfirm, Tag} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {connect, history} from 'umi'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import {downloadDocumentUrl} from '@/service/common/download'

import {
	getTableList,
	deleteRenewal,
	renewalAuditFlow,
} from '@/service/carMessage/renewal'
import Permissions from '@/components/Permissions'
import 'moment/locale/zh-cn'
import {approveStatus, renewalType} from '../dict'

const formItemLayout = {
	labelCol: {flex: '120px'},
	wrapperCol: {flex: '1'},
}

const renewalDom = (props: any) => {
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)
	const [tableList, setTableList] = useState<any[]>([])
	const [formData, setFormData] = useState<any[]>([])
	const [otherData, setOtherData] = useState<any>()

	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getTableList({
			...params,
			...otherData,
		})
			.then((res: any) => {
				if (res?.success) {
					setTableList(() => res.data.records)
					setTotal(res.data.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}

	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	// 删除事件
	const onDeleteFun = (ids: string) => {
		deleteRenewal(ids)
			.then((res) => {
				if (res?.success) {
					message.success(res.msg)
					onListFun()
				} 
			})
			.catch((err) => {
				message.error(err)
			})
	}

	// 流程作废
	const onAuditFlowFun = (record: {id: string; instanceId: string}) => {
		renewalAuditFlow({
			businessId: record?.id,
			instanceId: record?.instanceId,
			pass: '2',
			message: JSON.stringify({message: '已作废'}),
		})
			.then((res: {msg: string; success: boolean}) => {
				if (res?.success) {
					message.success(res.msg)
					onListFun()
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}
	// 列表
	const columns: ColumnsType<TargetAPI.TargetColumns> = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text, record, index) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '证照申请单号',
			dataIndex: 'renewalNo',
			align: 'center',
			width: 200,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '审核状态',
			dataIndex: 'approveStatus',
			align: 'center',
			width: 140,
			render: (text: any, record: any) => (
				<>
					{approveStatus?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === text) {
								return (
									<Tag color="processing" key={record?.id}>
										{item?.label}
									</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '补办类型',
			dataIndex: 'renewalType',
			align: 'center',
			width: 150,
			render: (text: any, record: any) => (
				<>
					{renewalType?.map((item: {key: number; label: string}) => {
						if (item?.key === text) {
							return (
								<Tag color="processing" key={record?.id}>
									{item?.label}
								</Tag>
							)
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '申请时间',
			dataIndex: 'renewalTime',
			align: 'center',
			width: 150,
			render: (text) => (
				<div>{moment(text).format('YYYY-MM-DD') || '--'}</div>
			),
		},
		{
			title: '补办费用',
			dataIndex: 'renewalFee',
			align: 'center',
			width: 150,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '申请人',
			dataIndex: 'renewalApply',
			align: 'center',
			width: 200,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text, record) => (
				<div>
					<Permissions permissionID="amc_assetCenter_carMessage_renewal_view">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/carMessage/renewal/view',
									query: {
										id: record.id,
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
					{record?.isAudit === 1 ? (
						<Permissions permissionID="amc_assetCenter_carMessage_renewal_process">
							<Button
								type="link"
								size="small"
								onClick={() => {
									history.push({
										pathname: '/carMessage/renewal/process',
										query: {
											id: record.id,
										},
									})
								}}>
								审核
							</Button>
						</Permissions>
					) : null}
					{String(record?.createUser) ===
					String(props?.user?.userId) ? (
						<>
							{record?.approveStatus === 3 ? (
								<Permissions permissionID="amc_assetCenter_carMessage_renewal_cancel">
									<Popconfirm
										placement="topLeft"
										title="你确定要作废这条数据吗？"
										onConfirm={() => onAuditFlowFun(record)}
										okText="确定"
										cancelText="取消">
										<Button type="link" size="small">
											作废
										</Button>
									</Popconfirm>
								</Permissions>
							) : null}

							{/* 		<Permissions permissionID="amc_assetCenter_carMessage_renewal_edit">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/carMessage/renewal/edit',
									query: {
										id: record.id,
									},
								})
							}}>
							编辑
						</Button>
					</Permissions> */}
							{record?.approveStatus === 4 ? (
								<>
									<Permissions permissionID="amc_assetCenter_carMessage_renewal_reissue">
										<Button
											type="link"
											size="small"
											onClick={() => {
												history.push({
													pathname:
														'/carMessage/renewal/edit',
													query: {
														id: record.id,
													},
												})
											}}>
											再次发起
										</Button>
									</Permissions>
									<Permissions permissionID="amc_assetCenter_carMessage_renewal_delete">
										<Popconfirm
											placement="topLeft"
											title="你确定要删除这条证照补办申请数据吗？"
											onConfirm={() =>
												onDeleteFun(record.id)
											}
											okText="确定"
											cancelText="取消">
											<Button type="link" size="small">
												删除
											</Button>
										</Popconfirm>
									</Permissions>
								</>
							) : null}
						</>
					) : null}
				</div>
			),
		},
	]

	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [otherData])

	// 搜索
	const onFinish = (values: any) => {
		const startTime: string =
			values.renewalDate &&
			moment(values?.renewalDate[0]).format('YYYY-MM-DD')
		const endTime: string =
			values.renewalDate &&
			moment(values?.renewalDate[1]).format('YYYY-MM-DD')
		setOtherData({
			renewalTimeStr: values?.renewalDate
				? `${startTime}~${endTime}`
				: null,
			renewalNo: values?.renewalNo || null,
			approveStatus: values?.approveStatus || null,
			renewalType: values?.renewalType || null,
		})
	}

	// 重置
	const onReset = () => {
		setOtherData({})
	}

	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						label: '证照申请单号',
						name: 'renewalNo',
						key: 'renewalNo',
					},
					{
						type: 'select',
						key: 'approveStatus',
						name: 'approveStatus',
						label: '审核状态',
						keys: 'key',
						title: 'label',
						items: [...approveStatus],
					},
					{
						type: 'dateRange',
						key: 'renewalDate',
						name: 'renewalDate',
						label: '申请时间',
					},
				],
			},
			{
				type: 'group',
				key: 'group2',
				groupItems: [
					{
						type: 'select',
						key: 'renewalType',
						name: 'renewalType',
						label: '补办类型',
						keys: 'key',
						title: 'label',
						items: [...renewalType],
					},
					{},
					{},
				],
			},
		]
		setFormData(formItems)
	}, [])

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Permissions permissionID="amc_assetCenter_carMessage_renewal_add">
						<Button
							type="primary"
							ghost
							size="small"
							onClick={() => {
								history.push({
									pathname: '/carMessage/renewal/add',
								})
							}}>
							新增
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_carMessage_renewal_export">
						<Button
							ghost
							size="small"
							className="btn_warning"
							onClick={() => {
								downloadDocumentUrl({
									resourceId: '118',
									queryDesc: '证照补办导出,resourceId:118',
									queryParam: otherData,
								})
							}}>
							导出
						</Button>
					</Permissions>
				</Space>
			</div>
			<div className="table">
				<CustomTable
					kid="id"
					params={params}
					columns={columns}
					pagination
					total={total}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={tableList}
				/>
			</div>
		</div>
	)
}

export default connect(({user}: any) => ({user}))(renewalDom)
